<template>
  <div class="dashboard-container">
    <!-- 欢迎横幅 -->
    <div class="welcome-banner">
      <div class="welcome-content">
        <h2>欢迎回来，{{ userStore.username || '管理员' }}！</h2>
        <p>今天是 {{ currentDate }}，祝您工作愉快！</p>
      </div>
      <div class="welcome-icon">
        <el-icon size="48" color="#409eff">
          <Sunny />
        </el-icon>
      </div>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card users-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon size="32">
                <User />
              </el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ statistics.users }}</div>
              <div class="stat-label">总用户数</div>
            </div>
            <div class="stat-trend">
              <el-icon color="#67c23a">
                <ArrowUp />
              </el-icon>
              <span>+12%</span>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card shadow="hover" class="stat-card roles-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon size="32">
                <Avatar />
              </el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ statistics.roles }}</div>
              <div class="stat-label">角色数量</div>
            </div>
            <div class="stat-trend">
              <el-icon color="#67c23a">
                <ArrowUp />
              </el-icon>
              <span>+5%</span>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card shadow="hover" class="stat-card permissions-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon size="32">
                <Lock />
              </el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ statistics.permissions }}</div>
              <div class="stat-label">权限数量</div>
            </div>
            <div class="stat-trend">
              <el-icon color="#67c23a">
                <ArrowUp />
              </el-icon>
              <span>+8%</span>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card shadow="hover" class="stat-card departments-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon size="32">
                <OfficeBuilding />
              </el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ statistics.departments }}</div>
              <div class="stat-label">部门数量</div>
            </div>
            <div class="stat-trend">
              <el-icon color="#67c23a">
                <ArrowUp />
              </el-icon>
              <span>+3%</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 主要内容区域 -->
    <el-row :gutter="20" class="main-content">
      <!-- 图表区域（横向排列，左侧） -->
      <el-col :span="16">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-card shadow="hover" class="chart-card" style="margin-bottom: 20px;">
              <template #header>
                <div class="card-header">
                  <span>能力雷达图</span>
                </div>
              </template>
              <div ref="chartRef1" style="width: 100%; height: 260px;"></div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card shadow="hover" class="chart-card" style="margin-bottom: 20px;">
              <template #header>
                <div class="card-header">
                  <span>部门柱状图</span>
                </div>
              </template>
              <div ref="chartRef2" style="width: 100%; height: 280px;"></div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card shadow="hover" class="chart-card" style="margin-bottom: 20px;">
              <template #header>
                <div class="card-header">
                  <span>权限分布饼图</span>
                </div>
              </template>
              <div ref="chartRef3" style="width: 100%; height: 260px;"></div>
            </el-card>
          </el-col>
        </el-row>
        <!-- 系统状态 -->
        <el-card shadow="hover" class="system-status-card">
          <template #header>
            <div class="card-header">
              <span>系统状态</span>
            </div>
          </template>
          <div class="system-status">
            <div class="status-item">
              <div class="status-label">CPU 使用率</div>
              <el-progress :percentage="systemStatus.cpu" :color="getStatusColor(systemStatus.cpu)" />
            </div>
            <div class="status-item">
              <div class="status-label">内存使用率</div>
              <el-progress :percentage="systemStatus.memory" :color="getStatusColor(systemStatus.memory)" />
            </div>
            <div class="status-item">
              <div class="status-label">磁盘使用率</div>
              <el-progress :percentage="systemStatus.disk" :color="getStatusColor(systemStatus.disk)" />
            </div>
          </div>
        </el-card>
      </el-col>
      <!-- 右侧：最近活动、快捷操作、最近登录 -->
      <el-col :span="8">
        <!-- 最近活动（与图表互换位置） -->
        <el-card shadow="hover" class="activity-card">
          <template #header>
            <div class="card-header">
              <span>最近活动</span>
              <el-button type="primary" size="small" @click="refreshActivity">
                <el-icon>
                  <Refresh />
                </el-icon>
                刷新
              </el-button>
            </div>
          </template>
          <el-table :data="recentActivity" style="width: 100%" :show-header="false">
            <el-table-column width="60">
              <template #default="{ row }">
                <el-avatar :size="40" :src="row.avatar">
                  {{ row.user.charAt(0) }}
                </el-avatar>
              </template>
            </el-table-column>
            <el-table-column>
              <template #default="{ row }">
                <div class="activity-item">
                  <div class="activity-user">{{ row.user }}</div>
                  <div class="activity-action">{{ row.action }}</div>
                  <div class="activity-time">{{ row.time }}</div>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
        <!-- 快捷操作 -->
        <el-card shadow="hover" class="quick-actions-card">
          <template #header>
            <div class="card-header">
              <span>快捷操作</span>
            </div>
          </template>
          <div class="quick-actions">
            <el-button
              type="primary"
              @click="handleQuickAction('users')"
              class="action-btn"
              @mouseenter="hoveredIndex = 0"
              @mouseleave="hoveredIndex = null"
              :class="{ 'is-hovered': hoveredIndex === 0, 'is-other-hovered': hoveredIndex !== null && hoveredIndex !== 0 }"
            >
              <el-icon><User /></el-icon>用户管理
            </el-button>
            <el-button
              type="success"
              @click="handleQuickAction('roles')"
              class="action-btn"
              @mouseenter="hoveredIndex = 1"
              @mouseleave="hoveredIndex = null"
              :class="{ 'is-hovered': hoveredIndex === 1, 'is-other-hovered': hoveredIndex !== null && hoveredIndex !== 1 }"
            >
              <el-icon><Avatar /></el-icon>角色管理
            </el-button>
            <el-button
              type="warning"
              @click="handleQuickAction('permissions')"
              class="action-btn"
              @mouseenter="hoveredIndex = 2"
              @mouseleave="hoveredIndex = null"
              :class="{ 'is-hovered': hoveredIndex === 2, 'is-other-hovered': hoveredIndex !== null && hoveredIndex !== 2 }"
            >
              <el-icon><Lock /></el-icon>权限管理
            </el-button>
            <el-button
              type="info"
              @click="handleQuickAction('departments')"
              class="action-btn"
              @mouseenter="hoveredIndex = 3"
              @mouseleave="hoveredIndex = null"
              :class="{ 'is-hovered': hoveredIndex === 3, 'is-other-hovered': hoveredIndex !== null && hoveredIndex !== 3 }"
            >
              <el-icon><OfficeBuilding /></el-icon>部门管理
            </el-button>
          </div>
        </el-card>
        <!-- 最近登录 -->
        <el-card shadow="hover" class="recent-logins-card">
          <template #header>
            <div class="card-header">
              <span>最近登录</span>
            </div>
          </template>
          <div class="recent-logins">
            <div v-for="login in recentLogins" :key="login.id" class="login-item">
              <el-avatar :size="32" :src="login.avatar">
                {{ login.username.charAt(0) }}
              </el-avatar>
              <div class="login-info">
                <div class="login-username">{{ login.username }}</div>
                <div class="login-time">{{ login.time }}</div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import {
  User,
  Avatar,
  Lock,
  OfficeBuilding,
  Sunny,
  ArrowUp,
  Refresh
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { dashboardAPI } from '@/api/auth'
import { ElMessage } from 'element-plus'

const router = useRouter()
const userStore = useUserStore()

// 当前日期
const currentDate = computed(() => {
  return new Date().toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    weekday: 'long'
  })
})

// 统计数据
const statistics = ref({
  users: 0,
  roles: 0,
  permissions: 0,
  departments: 0
})

// 获取统计数据
const fetchStatistics = async () => {
  try {
    const response = await dashboardAPI.getStatistics()
    if (response.code === 200 && response.value) {
      statistics.value = response.value
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 图表数据
const chartData = ref({
  departmentUserCount: {},
  activityTrend: [],
  permissionTypes: [],
  recentActivities: [],
  systemStatus: { cpu: 0, memory: 0, disk: 0 }
})

// 获取图表数据
const fetchChartData = async () => {
  try {
    const response = await dashboardAPI.getChartData()
    if (response.code === 200 && response.value) {
      chartData.value = response.value
      updateCharts()
    }
  } catch (error) {
    console.error('获取图表数据失败:', error)
  }
}

// 获取最近登录
const fetchRecentLogins = async () => {
  try {
    const response = await dashboardAPI.getRecentLogins()
    if (response.code === 200 && response.value) {
      recentLogins.value = response.value
    }
  } catch (error) {
    console.error('获取最近登录失败:', error)
  }
}

// 更新图表
const updateCharts = () => {
  updateRadarChart()
  updateBarChart()
  updatePieChart()
  updateSystemStatus()
  updateRecentActivity()
}

// 更新雷达图（用户活动趋势）
const updateRadarChart = () => {
  if (!chartInstance1 || !chartData.value.activityTrend) return

  const data = chartData.value.activityTrend.map(item => item.count)
  const dates = chartData.value.activityTrend.map(item => item.date)

  const option = {
    tooltip: {
      trigger: 'item'
    },
    radar: {
      indicator: dates.map(date => ({
        name: date,
        max: Math.max(...data) + 5
      })),
      radius: '65%',
      center: ['50%', '50%'],
      nameGap: 15,
      axisName: {
        fontSize: 10,
        color: '#666'
      }
    },
    series: [{
      name: '活动趋势',
      type: 'radar',
      data: [{
        value: data,
        name: '活动次数',
        itemStyle: {
          color: '#409eff'
        },
        areaStyle: {
          color: 'rgba(64, 158, 255, 0.2)'
        }
      }]
    }]
  }
  chartInstance1.setOption(option)
}

// 更新柱状图（部门用户分布）
const updateBarChart = () => {
  if (!chartInstance2 || !chartData.value.departmentUserCount) return

  const departments = Object.keys(chartData.value.departmentUserCount)
  const userCounts = Object.values(chartData.value.departmentUserCount)

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      top: '10%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: departments,
      axisLabel: {
        interval: 0,
        rotate: 45,
        fontSize: 10,
        color: '#666'
      },
      axisTick: {
        alignWithLabel: true
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        fontSize: 10
      }
    },
    series: [{
      data: userCounts,
      type: 'bar',
      barWidth: '50%',
      itemStyle: {
        color: '#409eff',
        borderRadius: [4, 4, 0, 0]
      },
      label: {
        show: true,
        position: 'top',
        fontSize: 10
      }
    }]
  }
  chartInstance2.setOption(option)
}

// 更新饼图（权限分布）
const updatePieChart = () => {
  if (!chartInstance3 || !chartData.value.permissionTypes) return

  // 为三个权限类别分配固定颜色
  const colorMap = {
    '读权限': '#409eff',    // 蓝色
    '写权限': '#67c23a',    // 绿色
    '管理权限': '#e6a23c'   // 橙色
  }

  const data = chartData.value.permissionTypes.map(item => ({
    value: item.value,
    name: item.name,
    itemStyle: {
      color: colorMap[item.name] || '#909399' // 默认灰色
    }
  }))

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      bottom: 10,
      left: 'center',
      itemWidth: 12,
      itemHeight: 8,
      textStyle: {
        fontSize: 11,
        color: '#666'
      }
    },
    series: [
      {
        name: '权限分布',
        type: 'pie',
        radius: ['35%', '65%'],
        center: ['50%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 8,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false
        },
        labelLine: {
          show: false
        },
        data,
        emphasis: {
          scale: true,
          scaleSize: 1.05,
          itemStyle: {
            shadowBlur: 15,
            shadowColor: 'rgba(0, 0, 0, 0.2)'
          }
        },
        selectedMode: 'single',
        selectedOffset: 8,
        animation: true,
        animationEasing: 'cubicOut',
        animationDurationUpdate: 500
      }
    ],
    graphic: []
  }
  chartInstance3.setOption(option)

  // 监听点击事件
  if (chartInstance3) {
    chartInstance3.off('click')
    chartInstance3.off('globalout')
    chartInstance3.off('downplay')
    chartInstance3.on('click', function(params) {
      if (params.componentType === 'series' && params.seriesType === 'pie') {
        chartInstance3.setOption({
          graphic: [{
            type: 'text',
            left: 'center',
            top: 'center',
            style: {
              text: params.data.name,
              fontSize: 16,
              fontWeight: 600,
              fill: params.color,
              textAlign: 'center',
              textVerticalAlign: 'middle'
            },
            z: 100
          }]
        })
      }
    })
    chartInstance3.on('globalout', function() {
      chartInstance3.setOption({ graphic: [] })
    })
    chartInstance3.on('downplay', function() {
      chartInstance3.setOption({ graphic: [] })
    })
  }
}

// 系统状态
const systemStatus = ref({
  cpu: 45,
  memory: 62,
  disk: 78
})

// 更新系统状态
const updateSystemStatus = () => {
  if (chartData.value.systemStatus) {
    systemStatus.value = chartData.value.systemStatus
  }
}

// 最近活动
const recentActivity = ref([])

// 更新最近活动
const updateRecentActivity = () => {
  if (chartData.value.recentActivities) {
    recentActivity.value = chartData.value.recentActivities
  }
}

// 最近登录
const recentLogins = ref([])

// 获取状态颜色
const getStatusColor = (percentage) => {
  if (percentage < 50) return '#67c23a'
  if (percentage < 80) return '#e6a23c'
  return '#f56c6c'
}

// 刷新活动数据
const refreshActivity = async () => {
  await fetchChartData()
  await fetchRecentLogins()
  ElMessage.success('数据已刷新')
}

// 快捷操作
const handleQuickAction = (action) => {
  switch (action) {
    case 'users':
      router.push('/users')
      break
    case 'roles':
      router.push('/roles')
      break
    case 'permissions':
      router.push('/permissions')
      break
    case 'departments':
      router.push('/departments')
      break
  }
}

const chartRef1 = ref(null)
const chartRef2 = ref(null)
const chartRef3 = ref(null)
let chartInstance1 = null
let chartInstance2 = null
let chartInstance3 = null

const hoveredIndex = ref(null)

// 组件挂载时获取数据
onMounted(async () => {
  // 获取统计数据
  await fetchStatistics()
  // 获取图表数据
  await fetchChartData()
  // 获取最近登录
  await fetchRecentLogins()

  console.log('仪表板数据加载完成')

  // 初始化图表
  if (chartRef1.value) {
    chartInstance1 = echarts.init(chartRef1.value)
    updateRadarChart()
    window.addEventListener('resize', () => chartInstance1 && chartInstance1.resize())
  }
  if (chartRef2.value) {
    chartInstance2 = echarts.init(chartRef2.value)
    updateBarChart()
    window.addEventListener('resize', () => chartInstance2 && chartInstance2.resize())
  }
  if (chartRef3.value) {
    chartInstance3 = echarts.init(chartRef3.value)
    updatePieChart()
    window.addEventListener('resize', () => chartInstance3 && chartInstance3.resize())
  }

  // 定时刷新数据（每5分钟）
  setInterval(async () => {
    await fetchChartData()
    await fetchRecentLogins()
  }, 5 * 60 * 1000)
})

onBeforeUnmount(() => {
  chartInstance1 && chartInstance1.dispose()
  chartInstance2 && chartInstance2.dispose()
  chartInstance3 && chartInstance3.dispose()
})
</script>

<style lang="scss" scoped>
.dashboard-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);

  // 欢迎横幅
  .welcome-banner {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 12px;
    padding: 30px;
    margin-bottom: 24px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: white;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);

    .welcome-content {
      h2 {
        margin: 0 0 8px 0;
        font-size: 24px;
        font-weight: 600;
      }

      p {
        margin: 0;
        opacity: 0.9;
        font-size: 14px;
      }
    }

    .welcome-icon {
      opacity: 0.8;
    }
  }

  // 统计卡片
  .stats-row {
    margin-bottom: 24px;

    .stat-card {
      border-radius: 12px;
      border: none;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.12);
      }

      .stat-content {
        display: flex;
        align-items: center;
        padding: 20px;

        .stat-icon {
          margin-right: 16px;
          padding: 12px;
          border-radius: 8px;
          background: rgba(64, 158, 255, 0.1);
          color: #409eff;
        }

        .stat-info {
          flex: 1;

          .stat-number {
            font-size: 28px;
            font-weight: 700;
            color: #303133;
            line-height: 1;
            margin-bottom: 4px;
          }

          .stat-label {
            font-size: 14px;
            color: #909399;
          }
        }

        .stat-trend {
          display: flex;
          align-items: center;
          font-size: 12px;
          color: #67c23a;
          font-weight: 500;

          .el-icon {
            margin-right: 4px;
          }
        }
      }

      &.users-card .stat-icon {
        background: rgba(64, 158, 255, 0.1);
        color: #409eff;
      }

      &.roles-card .stat-icon {
        background: rgba(103, 194, 58, 0.1);
        color: #67c23a;
      }

      &.permissions-card .stat-icon {
        background: rgba(230, 162, 60, 0.1);
        color: #e6a23c;
      }

      &.departments-card .stat-icon {
        background: rgba(245, 108, 108, 0.1);
        color: #f56c6c;
      }
    }
  }

  // 主要内容区域
  .main-content {

    .activity-card,
    .system-status-card,
    .quick-actions-card,
    .recent-logins-card {
      border-radius: 12px;
      border: none;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
      margin-bottom: 20px;

      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-weight: 600;
        color: #303133;
      }
    }

    // 活动列表
    .activity-item {
      .activity-user {
        font-weight: 600;
        color: #303133;
        margin-bottom: 4px;
      }

      .activity-action {
        color: #606266;
        font-size: 14px;
        margin-bottom: 2px;
      }

      .activity-time {
        color: #909399;
        font-size: 12px;
      }
    }

    // 系统状态
    .system-status {
      .status-item {
        margin-bottom: 20px;

        &:last-child {
          margin-bottom: 0;
        }

        .status-label {
          margin-bottom: 8px;
          font-weight: 500;
          color: #606266;
        }
      }
    }

    // 快捷操作
    .quick-actions {
      display: flex;
      flex-direction: column;
      gap: 12px;

      .action-btn {
        width: 100%;
        justify-content: flex-start;
        height: 44px;
        border-radius: 8px;
        font-weight: 500;
        transition: background 0.2s, box-shadow 0.2s, transform 0.15s, filter 0.2s;

        &.is-hovered {
          filter: brightness(1.08) drop-shadow(0 4px 16px #409eff33);
          transform: scale(1.04);
          z-index: 2;
        }
        &.is-other-hovered {
          filter: brightness(1.03) grayscale(0.1) opacity(0.92);
          box-shadow: 0 2px 8px 0 rgba(64, 158, 255, 0.10);
          z-index: 1;
        }

        .el-icon {
          margin-right: 8px;
        }
      }
    }

    // 最近登录
    .recent-logins {
      .login-item {
        display: flex;
        align-items: center;
        padding: 12px 0;
        border-bottom: 1px solid #f0f0f0;

        &:last-child {
          border-bottom: none;
        }

        .login-info {
          margin-left: 12px;
          flex: 1;

          .login-username {
            font-weight: 500;
            color: #303133;
            margin-bottom: 2px;
          }

          .login-time {
            font-size: 12px;
            color: #909399;
          }
        }
      }
    }
  }

  .chart-card {
    border-radius: 12px;
    border: none;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    margin-bottom: 20px;

    .card-header {
      font-weight: 600;
      color: #303133;
      padding-bottom: 10px;
    }
  }
}
</style>
